<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #slot-left>
          <span>共{{ total }}条记录</span>
        </template>
        <template #slot-right>
          <el-button
            v-power="'import'"
            type="danger"
            size="small"
            @click="$router.push('/excel')"
          >导入excel</el-button>
          <el-button
            v-power="'export'"
            type="success"
            size="small"
            @click="exportExcel"
          >导出excel</el-button>
          <el-button
            type="primary"
            size="small"
            @click="dialogFormVisible = true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px">
        <el-table
          :data="employeesList"
          border
          style="width: 100%"
          :default-sort="{ prop: 'workNumber', order: 'ascending' }"
        >
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column label="头像" align="center">
            <template slot-scope="scope">
              <!-- <img :src="scope.row.staffPhoto" alt=""> -->
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            :formatter="formatter"
          />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column label="入职时间" sortable>
            <template slot-scope="scope">
              <span>{{ scope.row.timeOfEntry | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="转正时间">
            <template slot-scope="scope">
              <span>{{ scope.row.correctionTime | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="assignRoleHandle(scope.row.id)">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                assign-role-handle
                @click="delEmployeesFn(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页区域 -->
        <el-pagination
          :current-page="query.page"
          :page-sizes="[10, 15, 20, 25]"
          :page-size="query.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
      <!-- 新增员工弹窗 -->
      <el-dialog
        title="新增员工"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="$refs.emDialog.resetForm()"
      >
        <EmDialog v-if="dialogFormVisible" ref="emDialog" @closee="closeFn" />
      </el-dialog>
      <!-- 分配角色弹窗 -->
      <el-dialog
        title="分配角色"
        :visible.sync="showAssignRole"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="showAssignRole=false"
      >
        <assignRole v-if="showAssignRole" :id="userId" @closeDialog="showAssignRole=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeesAPI, delEmployeesAPI } from '@/api/employees'
import employeesMethod from '@/constant/employees'
import EmDialog from './emDialog.vue'
import assignRole from './components/assignRole.vue'
import dayjs from 'dayjs'
export default {
  name: 'Employees',
  components: {
    EmDialog,
    assignRole
  },
  filters: {
    formatTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      dialogFormVisible: false, // 控制弹框的显示与否
      showAssignRole: false, // 分配角色弹窗是否显示
      userId: ''// 点击分配时的用户id
    }
  },
  created() {
    this.getEmployeesList()
  },
  methods: {
    // 处理表格数据方法
    formatData(rows) {
      // 枚举表头的准备
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 处理表头
      // 获取第一个数据的键名
      const one = Object.keys(rows[0])
      // 表头进行枚举
      const header = one.map(item => map[item])
      // 处理表格数据
      const data = rows.map(item => {
        item.correctionTime = dayjs(item.correctionTime).format('YYYY-MM-DD')
        item.timeOfEntry = dayjs(item.timeOfEntry).format('YYYY-MM-DD')
        item.formOfEmployment = this.formatter('', '', item.formOfEmployment)
        return Object.values(item)
      })
      return { header, data }
    },
    // 导出表格方法
    async exportExcel() {
      // 获取最新表格数据
      const res = await getEmployeesAPI(this.query)
      const rows = res.data.rows
      // 调用处理数据的方法
      const { header, data } = this.formatData(rows)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '员工信息', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // 格式化聘用形式数据
    formatter(row, column, cellValue, index) {
      // 导入枚举方法实现
      const obj = employeesMethod.hireType.find(
        (item) => Number(item.id) === Number(cellValue)
      )
      return obj ? obj.value : '未知'
    },
    // 获取员工列表数据
    async getEmployeesList() {
      const res = await getEmployeesAPI(this.query)
      this.employeesList = res.data.rows
      this.total = res.data.total
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeesList()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeesList()
    },
    // 删除员工
    delEmployeesFn(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          await delEmployeesAPI(row.id)
          if (this.employeesList.length === 1) {
            this.query.page--
            if (this.query.page <= 0) {
              this.query.page = 1
            }
          }
          this.getEmployeesList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 新增员工表单点击取消/确定,关闭
    closeFn() {
      this.dialogFormVisible = false
      this.getEmployeesList()
    },
    // 点击分配角色,触发的事件
    assignRoleHandle(id) {
      this.userId = id
      this.showAssignRole = true
    }

  }
}
</script>

<style lang="scss" scoped>
.el-pagination {
  text-align: center;
  margin-top: 20px;
}
</style>
